package org.openmrs.module.simplelabentry.web.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openmrs.Location;
import org.openmrs.Obs;
import org.openmrs.Order;
import org.openmrs.Patient;
import org.openmrs.api.context.Context;
import org.openmrs.module.hospitalcore.model.Lab;
import org.openmrs.module.simplelabentry.SimpleLabEntryService;
import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.view.RedirectView;

public class PrintLabOrderResultFormController extends SimpleFormController {

    /** Logger for this class and subclasses */
    protected final Log log = LogFactory.getLog(getClass());

    @Override
    protected Object formBackingObject(HttpServletRequest request) throws Exception {
        Patient patient = new Patient();
        return patient;
    }

    @Override
    protected Map referenceData(HttpServletRequest request, Object command, Errors errors) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        List<Order> orderList = new ArrayList<Order>();
        List<Order> allOrderList = new ArrayList<Order>();
        List<Patient> patientList = new ArrayList<Patient>();
        SimpleLabEntryService service = (SimpleLabEntryService) Context.getService(SimpleLabEntryService.class);
        Lab lab = service.getCurrentLab();
        map.put("patientIdType", lab.getPatientIdentifierType().getPatientIdentifierTypeId());
        String patientID = request.getParameter("patientIdentifier");
        String startDateStr = request.getParameter("orderDate");
        String endDateStr = request.getParameter("orderDate");
        String labNameStr = request.getParameter("labName");
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        Date startDate = sdf.parse(startDateStr);
        Date endDate = sdf.parse(endDateStr);
        Location location = Context.getLocationService().getLocation(1);
//        System.out.println("patientID " + patientID + " startDate = " + startDate + " endDate = " + endDate);
        List<Patient> allPatientList = Context.getPatientService().getPatients(request.getParameter("patientIdentifier"));
//        log.info("allPatientList size: '" + allPatientList.size() + "'");
        allOrderList = service.getLabOrdersBetweenDates(location, startDate, endDate,labNameStr, lab.getInvestigationsToDisplay(), lab.getLabOrderType());
        for (Order order : allOrderList) {
            if (allPatientList.contains(order.getPatient())) {
                String value = "";
                for (Obs currentObs : order.getEncounter().getObs()) {
                    if (order.getConcept().isNumeric()) {
                        if (currentObs.getValueNumeric() != null) {
                            value = currentObs.getValueNumeric().toString();
                        }
                    } else {
                        //log.info("obs = "+currentObs.getConcept());
                        value = currentObs.getValueAsString(Context.getLocale());
                    }
                    map.put(order.getConcept().getName().getName(), value);
                }
                patientList.add(order.getPatient());
                orderList.add(order);
            }
        }
        //encounterList = service.getLabOrderEncounters(location, startDate, endDate);
        map.put("orderList", orderList);
        map.put("patientList",patientList);
        return map;
    }

    @Override
    protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception {
        return new ModelAndView(new RedirectView(request.getContextPath() + getSuccessView()));
    }
}
